package Servlets;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet:: Download file form web site 
 * @author Guy
 *
 */
public class DownloadFileServlet  extends HttpServlet
{

	//NOTE: we using two session, the first is of Hibernate and the second is for session of email
	private static final long serialVersionUID = 1L;
	/**
	 * download an file form server -> get file name and file path parameters in request
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
	{
		String filePath =request.getParameter("FilePath");
		String fileName=request.getParameter("FileName");
		String filepath = filePath;
	
		BufferedInputStream buf = null;
		ServletOutputStream myOut = null;

		try {

			myOut = response.getOutputStream();
			File myfile = new File(filepath);
			
			//set response headers
			response.setContentType("text/plain");

			response.addHeader("Content-Disposition","attachment; filename=" + fileName);

			response.setContentLength((int) myfile.length());

			FileInputStream input = new FileInputStream(myfile);
			buf = new BufferedInputStream(input);
			int readBytes = 0;

			//read from the file; write to the ServletOutputStream
			while ((readBytes = buf.read()) != -1)
				myOut.write(readBytes);

		} 
		catch (IOException ioe) 
		{

			throw new ServletException(ioe.getMessage());

		}
		finally
		{

			//close the input/output streams
			if (myOut != null)
				myOut.close();
			if (buf != null)
				buf.close();

		}

	}	
}

